import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> nodes = new LinkedList<>();
        if (root != null) {
            nodes.add(root);
        }
        int pre = 1;
        while (nodes.size() != 0) {
            List<Integer> list = new ArrayList<>();
            int n = pre;
            pre = 0;
            for (int i = 0; i < n; i++) {
                TreeNode node = nodes.poll();
                assert node != null;
                list.add(node.val);
                if (node.left != null) {
                    nodes.offer(node.left);
                    pre++;
                }
                if (node.right != null) {
                    nodes.offer(node.right);
                    pre++;
                }
            }
            res.add(new ArrayList<>(list));
        }
        return res;
    }
}
